package com.pgybook.front.web.util;

import jodd.typeconverter.TypeConverterManager;
import jodd.util.StringUtil;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebArgumentResolver;
import org.springframework.web.context.request.NativeWebRequest;

/**
 * Created with IntelliJ IDEA.
 * User: feeling
 * Date: 13-11-21
 * Time: 下午4:11
 */
public class SessionAttrInjector implements WebArgumentResolver {
    @Override
    public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) throws Exception {
        if (methodParameter.hasParameterAnnotation(Session.class)) {
            Session session = methodParameter.getParameterAnnotation(Session.class);
            String attributeName = session.value();
            if (StringUtil.isBlank(attributeName)) {
                attributeName = methodParameter.getParameterName();
            }
            if (StringUtil.isBlank(attributeName)) {
                return UNRESOLVED;
            }
            Object value = webRequest.getAttribute(attributeName, 1);
            if (value == null) {
                return null;
            } else {
                Class<?> mType = methodParameter.getParameterType();
                return TypeConverterManager.getDefaultTypeConverterManager().convertType(value, mType);
            }
        } else if (methodParameter.hasParameterAnnotation(Request.class)) {
            Request aRequest = methodParameter.getParameterAnnotation(Request.class);
            String attributeName = aRequest.value();
            if (StringUtil.isBlank(attributeName)) {
                attributeName = methodParameter.getParameterName();
            }
            if (StringUtil.isBlank(attributeName)) {
                return UNRESOLVED;
            }
            Object value = webRequest.getAttribute(attributeName, 0);
            if (value == null) {
                return null;
            } else {
                Class<?> mType = methodParameter.getParameterType();
                return TypeConverterManager.getDefaultTypeConverterManager().convertType(value, mType);
            }
        }
        return UNRESOLVED;
    }

}
